package com.zyfdroid.bigdialerkit;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import com.zyfdroid.bigdialerkit.utils.BaseActivity;

import java.util.ArrayList;

public class ContactActivity extends BaseActivity {

    View pageMain;
    View pageDetail;
    View pageDelete;

    Button btnDialTo;
    TextView txtDeleteConfirmName;
    ListView listView;
    ContactAdapter contactAdapter;
    ArrayList<ContactInfo> contactInfos;

    private void initUI(){
        pageMain = findViewById(R.id.pageContactMain);
        pageDetail = findViewById(R.id.pageContactDetail);
        pageDelete = findViewById(R.id.pageContactDelete);
        btnDialTo = findViewById(R.id.btnContactDialTo);
        txtDeleteConfirmName = findViewById(R.id.txtContactDeleteConfirmName);
        pageDelete.setVisibility(View.GONE);
        pageDetail.setVisibility(View.GONE);
    }



    @Override
    protected void onCreate( Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_contact);
        selectedPhone = "";
        initUI();
        initAdapter();
        loadData();
    }

    private void initAdapter(){
        contactInfos = new ArrayList<>();
        contactAdapter = new ContactAdapter(contactInfos, this);
        listView = findViewById(R.id.listContact);
        listView.setAdapter(contactAdapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                ContactInfo contact = (ContactInfo) parent.getItemAtPosition(position);
                onEntrySelected(contact.name, contact.phoneNumber,contact.contactId);
            }
        });
    }

    private void loadData(){
        // 清空现有的联系人列表数据
        contactInfos.clear();
        try {
            // 执行联系人查询
            String[] projection = new String[] {
                    ContactsContract.Data.CONTACT_ID,
                    ContactsContract.Data.DISPLAY_NAME,
                    ContactsContract.CommonDataKinds.Phone.NUMBER
            };

            // 查询系统联系人数据
            Cursor cursor = getContentResolver().query(
                    ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                    projection,
                    null,
                    null,
                    null
            );

            // 遍历查询结果，将数据存入ArrayList<ContactInfo>
            if (cursor != null && cursor.getCount() > 0) {
                while (cursor.moveToNext()) {
                    @SuppressLint("Range") String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Data.CONTACT_ID));
                    @SuppressLint("Range") String displayName = cursor.getString(cursor.getColumnIndex(ContactsContract.Data.DISPLAY_NAME));
                    @SuppressLint("Range") String phoneNumber = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                    // 创建ContactInfo对象
                    ContactInfo contact = new ContactInfo(displayName, phoneNumber,contactId);
                    // 将ContactInfo对象添加到ArrayList中
                    contactInfos.add(contact);
                }
                cursor.close();
            }
        }catch (Exception ex){
            showToast("读取电话失败");
        }
        // 通知适配器数据已发生改变
        contactAdapter.notifyDataSetChanged();
    }

    public static class ContactInfo{
        public ContactInfo(String name, String phoneNumber,String contactId) {
            this.name = name;
            this.phoneNumber = phoneNumber;
            this.contactId = contactId;
        }

        public String name;
        public String phoneNumber;
        public String contactId;
    }

    public class ContactAdapter extends BaseAdapter {
        private ArrayList<ContactInfo> contactList;
        private Context context;

        public ContactAdapter(ArrayList<ContactInfo> contactList, Context context) {
            this.contactList = contactList;
            this.context = context;
        }

        @Override
        public int getCount() {
            return contactList.size();
        }

        @Override
        public Object getItem(int position) {
            return contactList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;

            if (convertView == null) {
                convertView = getLayoutInflater().inflate(R.layout.adapter_contact, parent, false);
                holder = new ViewHolder();
                holder.nameTextView = convertView.findViewById(R.id.txtAdapterContactName);
                holder.phoneTextView = convertView.findViewById(R.id.txtAdapterContactPhone);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            ContactInfo contact = contactList.get(position);
            holder.nameTextView.setText(contact.name);
            holder.phoneTextView.setText(contact.phoneNumber);

            return convertView;
        }

        private class ViewHolder {
            TextView nameTextView;
            TextView phoneTextView;
        }
    }


    private String selectedPhone = "";
    private String selectedContactId = "";

    private void onEntrySelected(String name,String tel,String cid){
        selectedPhone = tel;
        selectedContactId = cid;
        btnDialTo.setText("打电话给\n"+name);
        txtDeleteConfirmName.setText(name);
        pageMain.setVisibility(View.GONE);
        pageDelete.setVisibility(View.GONE);
        pageDetail.setVisibility(View.VISIBLE);
    }


    public void contactDialTo(View view) {
        if(!TextUtils.isEmpty(selectedPhone)){
            callPhone(selectedPhone);
        }
    }

    public void contactDeleteContact(View view) {
        pageMain.setVisibility(View.GONE);
        pageDelete.setVisibility(View.VISIBLE);
        pageDetail.setVisibility(View.GONE);
    }

    public void contactGoBack(View view) {
        selectedPhone = "";
        pageMain.setVisibility(View.VISIBLE);
        pageDelete.setVisibility(View.GONE);
        pageDetail.setVisibility(View.GONE);
    }

    public void contactConfirmDeleteContact(View view) {
        try {
            deleteContactById(selectedContactId);
        }catch (Exception ex){
            ex.printStackTrace();
            showToast("删除失败");
            return;
        }
        pageMain.setVisibility(View.VISIBLE);
        pageDelete.setVisibility(View.GONE);
        pageDetail.setVisibility(View.GONE);
        selectedPhone = "";
        loadData();
        showToast("删除成功");
    }

    private void deleteContactById(String contactId) {
        // 定义删除操作的where子句
        String where = ContactsContract.Data.CONTACT_ID + " = ? ";
        // 定义where子句中的参数值
        String[] params = new String[] {contactId};

        // 删除联系人
        getContentResolver().delete(ContactsContract.RawContacts.CONTENT_URI, where, params);
    }

    private void deleteContact(String phoneNumber) {
        ContentResolver contentResolver = getContentResolver();

        // 查询联系人数据表，根据电话号码查找联系人ID
        Cursor cursor = contentResolver.query(
                ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                new String[]{ContactsContract.CommonDataKinds.Phone.CONTACT_ID},
                ContactsContract.CommonDataKinds.Phone.NUMBER + " = ?",
                new String[]{phoneNumber},
                null
        );

        // 如果找到匹配的联系人
        if (cursor != null && cursor.moveToFirst()) {
            do {
                @SuppressLint("Range") String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));

                // 根据联系人ID删除联系人
                contentResolver.delete(ContactsContract.RawContacts.CONTENT_URI,
                        ContactsContract.RawContacts.CONTACT_ID + " = ?",
                        new String[]{contactId});
            } while (cursor.moveToNext());
        }

        if (cursor != null) {
            cursor.close();
        }
    }

    @Override
    public void onBackPressed() {
        if(pageDelete.getVisibility() == View.VISIBLE){
            contactCancelDeleteContact(null);
            return;
        }
        if(pageDetail.getVisibility() == View.VISIBLE){
            contactGoBack(null);
            return;
        }
        super.onBackPressed();
    }

    public void contactCancelDeleteContact(View view) {
        pageMain.setVisibility(View.GONE);
        pageDelete.setVisibility(View.GONE);
        pageDetail.setVisibility(View.VISIBLE);
    }
}
